package com.itshizhan.itjidancideveloper.utils;

import com.itshizhan.itjidancideveloper.constants.Constants;
import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Map;

public class JwtUtils {

	// token 过期时间, 单位: 毫秒. 这个值表示 30 天,
	// 测试3分钟过期  Constants.TimesValue.Min_1 * 3
	private static final long TOKEN_EXPIRED_TIME = Constants.TimesValue.Day_1 * 30;
	//setId使用, jwt唯一标识
	public static final String jwtId = "itjidanciToken";
	//jwt 加密解密密钥，生产环境请保存到配置中心，不对外暴露
	private static final String JWT_SECRET = "jdcdotitshizhandotcomTgzMjYyN2I0ZjY=135790";

	/**
	 * @param claims: 可以是map、bean或字符串，这里使用map封装
	 * @return 返回token
	 */
	public static String createJWT(Map<String, Object> claims) {

		// 使用秘钥签名生产key
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		byte[] keyBytes = JWT_SECRET.getBytes();
		SecretKeySpec secretKey = new SecretKeySpec(keyBytes, signatureAlgorithm.getJcaName());
		//签发时间
		Date now = new Date(System.currentTimeMillis());
		long nowMillis = System.currentTimeMillis();
		JwtBuilder builder = Jwts.builder()
				//设置claims,必须先设置Claims，在设置过期时间，顺序不能乱
				.setClaims(claims)
				//设置jti(JWT ID)：是JWT的唯一标识
				.setId(jwtId)
				//iat: jwt的签发时间
				.setIssuedAt(now)
				//设置签名使用的签名算法和签名使用的秘钥
				.signWith(secretKey,signatureAlgorithm);
		if (TOKEN_EXPIRED_TIME >= 0) {
			//String jwt = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 3600000)).compact();
			System.out.println(nowMillis);
			System.out.println(TOKEN_EXPIRED_TIME);
			long expMillis = nowMillis + TOKEN_EXPIRED_TIME;
			System.out.println(expMillis);
			Date exp = new Date(expMillis);
			//设置过期时间
			System.out.println(exp);
			builder.setExpiration(exp);
		}
		return builder.compact();
	}


	/**
	 * 解析JWT
	 * @param jsonWebToken
	 * @return
	 */
	public static Claims parseJWT(String jsonWebToken) {
		try {
			SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
			byte[] keyBytes = JWT_SECRET.getBytes();
			SecretKeySpec secretKey = new SecretKeySpec(keyBytes, signatureAlgorithm.getJcaName());
			return Jwts.parserBuilder()
					.setSigningKey(secretKey)
					.build()
					.parseClaimsJws(jsonWebToken)
					.getBody();
		} catch (JwtException e) {
			e.printStackTrace();
			System.out.println("Token解析失败，过期了");
			return null;
		}
	}


	//测试
	public static void main(String[] args) {
//		Map<String, Object> claims = new HashMap<>();
		//		claims.put("id", "198250649279582234");
		//		claims.put("userName", "itshizhan");
		//		claims.put("role", "0");
		//		claims.put("email", "itshizhan.com");
		//		String token = JwtUtils.createJWT(claims);
		//		System.out.println(token);


		//String jtoken = "eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiMCIsImlkIjoiMTk4MjUwNjQ5Mjc5NTgyMjM0IiwidXNlck5hbWUiOiJpdHNoaXpoYW4iLCJlbWFpbCI6Iml0c2hpemhhbi5jb20iLCJqdGkiOiJpdGppZGFuY2lUb2tlbiIsImlhdCI6MTYxNjE0MjM3MiwiZXhwIjoxNjE2MTQyNTUyfQ.gvPsLXaKqLoC0fcBsUy_sy0vmmwoAZ0fKV8K0Tx1a20";
		//		try {
		//			Claims claims1 = JwtUtils.parseJWT(jtoken);
		//			System.out.println(claims1);
		//			if (claims1!=null){
		//				System.out.println(claims1.getExpiration());
		//				System.out.println(claims1.get("id"));
		//				System.out.println(claims1.get("userName"));
		//				System.out.println(claims1.get("role"));
		//				System.out.println(claims1.get("email"));
		//			}
		//		}catch (Exception e){
		//			System.out.println("token过期了");
		//			//e.printStackTrace();
		//		}
		//		System.out.println("end");

	}

}
